﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace Utility
{
    /// <summary>
    /// Function	:	Log record
    /// Author	:		Xiaojun.Liu
    /// Create date	:	2006.09.19
    /// Modify date :	
    /// Description	:
    /// Remark :		
    /// </summary>
    public class Log
    {
        /// <summary>
        /// 文件存储路径
        /// </summary>
        private static string filePath;

        /// <summary>
        /// 取得日志文件路径及名称 = 系统名称+日期
        /// </summary>
        /// <returns></returns>
        private static string GetLogFilePath()
        {
            string _filePath = System.Configuration.ConfigurationManager.AppSettings["LogFilePath"].ToString();

            string _logFileName = System.Configuration.ConfigurationManager.AppSettings["SystemName"].ToString();

            _filePath += _logFileName;
            _filePath += System.DateTime.Now.Year.ToString();
            _filePath += System.DateTime.Now.Month.ToString().Length < 2 ? ("0" + System.DateTime.Now.Month.ToString()) : System.DateTime.Now.Month.ToString();
            _filePath += System.DateTime.Now.Day.ToString().Length < 2 ? ("0" + System.DateTime.Now.Day.ToString()) : System.DateTime.Now.Day.ToString();
            _filePath += ".log";

            return _filePath;
        }



        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="componentName">内容名称</param>
        /// <param name="message">消息</param>
        public static void Write(string componentName, string message)
        {
            filePath = GetLogFilePath();

            Mutex mutex = new Mutex(false);

            try
            {
                mutex.WaitOne();

                FileStream fs = new FileStream(filePath, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("[" + System.DateTime.Now.ToLongTimeString() + "] [Debug] [" + componentName + "]");
                sw.WriteLine("Msg: " + message);
                sw.WriteLine();
                sw.Close();
            }
            catch(IOException e)
            {
                throw e;
            }
            finally
            {

                if (mutex != null)
                {
                    mutex.Close();
                }
            }
        }



    }//
}
